/**
 * use list
 */

layui.use(['form', 'table', 'tableSelect'], function () {
    var $ = layui.jquery,
        form = layui.form,
        tableSelect = layui.tableSelect,
        table = layui.table;
    let searchFieldsetStatus=localStorage.getItem("searchFieldsetStatus");
    if(searchFieldsetStatus=='0')
    {
        $(".search-display-btn").attr("show","0");
        $(".search-display-btn").html('<i class="fa fa-angle-down"></i>展开');
        $($('.layui-form')[0]).hide();
    }
    let u=localStorage.getItem("a@m");
    let loginU={};
    if(u==undefined){
        // layer.msg('请登录', {icon: 1, time: 500},function () {window.location = 'logout';});
    }else{
        loginU=decryptLocalStorage(u);
    }
    setTableHeight();
    //system=超级管理员；nation=国家账号；province=省级账号；city=市级账号；district=区级账号；school=学校账号；teacher=教师账号
    let tableUrl=baseUrl+"admin/v1/user/page?token="+loginU.token;
    table.render({
        elem: '#currentTableId',
        url: tableUrl,loginUserType:loginU.userType,
        where: {
            keyWord: JSON.stringify({})
        },
        toolbar: '#toolbarPanel',
        defaultToolbar: [],
        cols: [[
            {type: "checkbox", align:"center", width: 50},
            {field: 'userId', align:"center", width: 80, title: 'ID', sort: true},
            {field: 'userName', align:"center", title: '账号', sort: true},
            {field: 'trueName', align:"center",  title: '姓名', sort: true},
            {field: 'userType', align:"center",  title: '账号类型', sort: true,
                templet : function(data) {
                    if(data.userType=='system')
                    {
                        return "超级管理员";
                    }
                    else if(data.userType=='nation')
                    {
                        return "国家账号";
                    }
                    else if(data.userType=='province')
                    {
                        return "省级账号";
                    }
                    else if(data.userType=='city')
                    {
                        return "市级账号";
                    }
                    else if(data.userType=='district')
                    {
                        return "区级账号";
                    }
                    else if(data.userType=='school')
                    {
                        return "学校账号";
                    }
                    else if(data.userType=='teacher')
                    {
                        return "教师账号";
                    }
                    else
                    {
                        return "其他"
                    }
                }},
            // {field: 'roleName', align:"center",  title: '角色', sort: true},
            {field: 'sex', align:"center",  title: '性别', sort: true},
            {field: 'mobile', align:"center",  title: '手机号码', sort: true},
            {title: '操作', minWidth: 220, toolbar: '#currentTableBar', align: "center"}
        ]],
        limits: [10, 15, 20, 25, 50, 100, 200, 300,500],
        limit: 20,
        page: true,
        skin: 'line',parseData: function (res) {
            for (let i in res.data) {
                res.data[i].loginUserType = loginU.userType;
            }
            return res;
        },
        done: function(res, curr, count){
            if(res.code===-1)
            {
                layer.msg('请登录', {icon: 1, time: 500},function () {
                    //window.location = 'logout';
                });
                return;
            }
            if(loginU.userType=='system' ) {
                $(".del-power-btn").css({"display":"inline-block"});
            }
            setTableHeight();

        }
    });


    let curr=1;
    let keyWord="{}";
    // 监听搜索操作
    form.on('submit(data-search-btn)', function (data) {
        keyWord = JSON.stringify(data.field);
        //执行搜索重载
        table.reload('currentTableId', {
            page: {
                curr: 1
            }
            , where: {
                keyWord: keyWord
            }
        }, 'data');

        return false;
    });

    /***
     *  双击列表记录
     */
    table.on('rowDouble(currentTableFilter)', function(obj){
        let data = obj.data;
        return;layer.msg('双击列表记录！', {
            icon: 2,
            time: 2000
        });
        return;
    })

    form.on('submit(data-export-btn)', function (data) {
        keyWord = JSON.stringify(data.field);
        layer.load(2, {shade: [0.5, '#fff']});
        request.otherGetMethod("user","exportData",{token:loginU.token,keyWord: keyWord},function(data){
            layer.closeAll();
            if(data.data!='')
            {
                location.href=data.data;
            }else{
                layer.msg('导出Excel出错！', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
        });

        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if(obj.event==='import')
        {
            let index=layer.open({
                title: '导入',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: false,
                area: ['100%', '100%'],
                content: '/page/system/user/import',
                end : function() {
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr:curr
                        }
                        , where: {
                            keyWord: keyWord
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        }else if (obj.event === 'add') {  // 监听添加操作
            localStorage.removeItem('userData');
            var index = layer.open({
                title: '添加用户',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '/page/system/user/edit',
                end : function() {
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: 1
                        }
                        , where: {
                            keyWord: keyWord
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        } else if (obj.event === 'delete') {  // 监听删除操作
            if(loginU.userType!='system')
            {
                layer.msg('只能超级管理员操作删除', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            let params={token:loginU.token,ids:''};
            let ids='';
            if(data.length>0){
                for(let i=0;i<data.length;i++){
                    if(data[i].userName=='admin')
                    {
                        layer.msg('admin不能删除', {
                            icon: 2,
                            time: 2000
                        });
                        return;
                    }
                    ids+=data[i].userId+',';
                }
                ids=ids.substring(0,ids.length-1);
            }
            params.ids=ids;
            let index=layer.confirm("确认删除账号，请谨慎操作？", {
                btn: ["确定", "取消"]
            }, function (index) {
                layer.close(index);
                request.delList('user',params,function(result){
                    if(result.code==0){
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 500
                        },function () {
                            //执行搜索重载
                            table.reload('currentTableId', {
                                page: {
                                    curr: 1
                                }
                                , where: {
                                    keyWord: keyWord
                                }
                            }, 'data');
                        });
                    }else{
                        layer.msg(result.msg ||'删除失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                });


            }, function (index) {
                layer.close(index);
            });


        }
    });

    //监听表格复选框选择
    table.on('checkbox(currentTableFilter)', function (obj) {
        //console.log(obj)
    });

    table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            localStorage.setItem("userData", encryptLocalStorage(data,loginU.token));
            var index = layer.open({
                title: '编辑用户',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: false,
                area: ['80%', '80%'],
                content: '/page/system/user/edit',
                end : function() {
                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: 1
                        }
                        , where: {
                            keyWord: keyWord
                        }
                    }, 'data');
                }

            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;
        } else if (obj.event === 'delete') {
            if(loginU.userType!='system')
            {
                layer.msg('只能超级管理员操作删除', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
            if(data.userName=='admin')
            {
                layer.msg('admin不能删除', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
            let index=layer.confirm("确认删除账号，请谨慎操作？", {
                btn: ["确定", "取消"]
            }, function (index) {
                layer.close(index);
                request.del('user',{token:loginU.token,id:obj.data.userId},function(result){
                    if(result.code==0){
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 500
                        },function () {
                            obj.del();
                        });
                    }else{
                        layer.msg(result.msg ||'删除失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                });

            }, function () {
                layer.close(index);
            });


        }
    });


});